package conf

import (
	"sync"
)

var (
	configuration = &Configuration{} // 配置[待废弃]使用conf_default.go中的defaultConf
)

type Configuration struct {
	settings   Settings
	dataSource []IAdapter
	initOnce   sync.Once
}

func (c *Configuration) Initialize(opts ...func(c *Configuration)) error {
	var berr error
	c.initOnce.Do(func() {
		for _, opt := range opts {
			opt(c)
		}
		needInitAdapter := c.dataSource
		c.dataSource = []IAdapter{}

		for _, t := range needInitAdapter {
			if err := t.Initialize(c); err != nil {
				if err == Err_UnNeedLoadAdapter {
					continue
				} else {
					berr = err
					return
				}
			}
			c.dataSource = append([]IAdapter{t}, c.dataSource...)
		}
	})
	return berr
}
func InitWithAdapter(a IAdapter) func(c *Configuration) {
	return func(c *Configuration) {
		c.dataSource = append(c.dataSource, a)
	}
}

// 设置配置
func setConfig(data map[string]interface{}) {
	var recursionSetConfig func(key string, d map[string]interface{})
	recursionSetConfig = func(key string, d map[string]interface{}) {
		for k, v := range d {
			if vv, ok := v.(map[string]interface{}); ok {
				recursionSetConfig(key+k+".", vv)
			} else {
				configuration.SetConfig(key+k, v)
			}
		}
	}
	recursionSetConfig("", data)
}
func (c *Configuration) SetConfig(key string, value interface{}) {
	c.settings.SetConfig(splitConfigKey(key), value)
}
